package com.hnucm.c201901020241.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.discuss.Discuss_post_information;
import com.hnucm.c201901020241.discuss.Disscuss_item;
import com.hnucm.c201901020241.pojo.Content;
import com.hnucm.c201901020241.utils.BlurTransformation;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class TabFragment extends Fragment {
    String type;
    List<Content>contentList;
    RecyclerView recyclerView;
    RecyclerAdapter recyclerAdapter;

    public TabFragment(String type) {
        this.type = type;
    }

    public static Fragment newInstance(String title) {
        TabFragment fragment = new TabFragment(title);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        contentList=new ArrayList<>();
        View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //      在这里可以选择传参过去，然后发送请求获得相应的数据,现在这里发请求获得一个对象的列表，然后将这个列表发过去。
//        按照回复数返回所有的帖子
        x.Ext.init(getActivity().getApplication());
        RequestParams requestParams=new RequestParams("http://121.4.27.254:8090/queryContentListbycomments");
        //requestParams.addQueryStringParameter("type",type);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("TabFragment","result"+result);
                try {
                    JSONArray jsonArray=new JSONArray(result);
                    for(int i=0;i<jsonArray.length();i++){
                        Content content=new Content();
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        content.title=jsonObject.getString("title");
                        content.name=jsonObject.getString("name");
                        content.time=jsonObject.getString("time");
                        content.base64=jsonObject.getString("base64");
                        content.account=jsonObject.getString("account");
                        content.title_discuss=jsonObject.getString("title_discuss");
                        content.minformation=jsonObject.getString("minformation");
                        contentList.add(content);
                    }
                    recyclerAdapter=new RecyclerAdapter();
                    recyclerView.setAdapter(recyclerAdapter);
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    recyclerView.setLayoutManager(layoutManager);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


//刷新
        RefreshLayout refreshLayout = (RefreshLayout)getActivity().findViewById(R.id.SmartRefreshLayout1);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                contentList.clear();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                x.Ext.init(getActivity().getApplication());
                RequestParams requestParams=new RequestParams("http://121.4.27.254:8090/queryContentListbycomments");
                //requestParams.addQueryStringParameter("type",type);
                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.i("TabFragment","result"+result);
                        try {
                            JSONArray jsonArray=new JSONArray(result);
                            for(int i=0;i<jsonArray.length();i++){
                                Content content=new Content();
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                content.title=jsonObject.getString("title");
                                content.name=jsonObject.getString("name");
                                content.time=jsonObject.getString("time");
                                content.base64=jsonObject.getString("base64");
                                content.title_discuss=jsonObject.getString("title_discuss");
                                content.minformation=jsonObject.getString("minformation");
                                content.account=jsonObject.getString("account");
                                contentList.add(content);
                            }
                            recyclerAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }
        });


//        重新加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {

                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });



    }


    class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.AuthorViewHolder> {


        @Override
        public RecyclerAdapter.AuthorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View childView = inflater.inflate(R.layout.item, parent, false);
            RecyclerAdapter.AuthorViewHolder viewHolder = new RecyclerAdapter.AuthorViewHolder(childView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(RecyclerAdapter.AuthorViewHolder holder, int position) {
            System.out.println(contentList.get(position).title_discuss);
            holder.titleTv.setText(contentList.get(position).title);
            holder.nameTv.setText(contentList.get(position).name);
            holder.timeTv.setText(contentList.get(position).time);
            holder.title_discussTv.setText(contentList.get(position).title_discuss);
            holder.inforTv.setText(contentList.get(position).minformation);
//            base64图片的处理
            System.out.println(contentList.get(position).base64);
            byte[] imageBytes = Base64.decode(contentList.get(position).base64, Base64.DEFAULT);
            Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);

            Glide.with(getActivity()).load(decodedImage)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(holder.imageView);


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    这里是点击跳转到详细的帖子页面
                    Intent intent=new Intent(getActivity(), Discuss_post_information.class);
                    intent.putExtra("title_discuss",contentList.get(position).title_discuss);
                    intent.putExtra("account",contentList.get(position).account);
                    intent.putExtra("time",contentList.get(position).time);
                    intent.putExtra("name",contentList.get(position).name);
                    intent.putExtra("mainInformation",contentList.get(position).minformation);
//                    这个base64是这个楼主的
                    intent.putExtra("base64",contentList.get(position).base64);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return contentList.size();
        }


        class AuthorViewHolder extends RecyclerView.ViewHolder {

            TextView titleTv,nameTv,timeTv,title_discussTv,inforTv;
            ImageView imageView;
            public AuthorViewHolder(View itemView) {
                super(itemView);
                titleTv=itemView.findViewById(R.id.textView20);
                nameTv=itemView.findViewById(R.id.textView27);
                timeTv=itemView.findViewById(R.id.textView35);
                title_discussTv=itemView.findViewById(R.id.textView36);
                inforTv=itemView.findViewById(R.id.textView37);
                imageView=itemView.findViewById(R.id.circleImageView);
            }
        }
    }
}
